package person.bangbang.im.Androidgin.Framework;

import java.util.ArrayList;
import java.util.List;

import person.bangbang.im.Androidgin.Util.Log;


/**
 * all chats we take participate in, 
 * whatever account, whatever group.
 * 
 * one to one chat only.
 */
public class Conversations {
	private static final String TAG = "Androidgin.Chats";
	
	// TODO remove this field, should 
	// independently with Android-specific
	// DONE it doesn't matter, just a name-war.
	/* whenever new a chat increase this by 1 */
	private int _notifyId = 0;
	
	private static Conversations _instance;
	
	private List<Conversation> mList = new ArrayList<Conversation>();
	
	private List<OnConversationsEvent> mListener = new ArrayList<OnConversationsEvent>();
	
	private Conversations(){
		
	}
	
	public static Conversations getInstance(){
		if (null == _instance) {
			_instance = new Conversations();
		}
		
		return _instance;
	}
	
	protected void addConversation(Conversation c) {
		if (null == c) {
			return;
		}
		mList.add(c);
	}
	public void removeConversation(Conversation c) {
		for (OnConversationsEvent e : mListener) {
			e.onDelete(c);
		}
		
		mList.remove(c);

	}
	
	/**
	 * if there is no one, create it.
	 * @param b
	 * @return
	 */
	public Conversation getOrNewConversation(Buddy b) {

		
		for (Conversation c : mList) {
			if (Conversation.TYPE_IM == c.getType()) { // not a room chatting, always in zero positon.
				if (c.getPartners().get(0).getID() == b.getID()) {
					return c;
				}
			} else {
				throw new RuntimeException("unImplements..");
			}
		}
		
		Log.d(TAG, "create a chat with buddy: " + b.getID());
		/* ++i VS i++ */
		Conversation c = new Conversation(b, ++_notifyId);
		addConversation(c);
		
		for (OnConversationsEvent e : mListener) {
			e.onNew(c);
		}
		
		return c;
	}
	
	/**
	 * find chat with which you talk.
	 * 
	 * @param partner
	 * @return
	 */
	public Conversation findConversation(Buddy partner) {
		for (Conversation cc : mList) {
			if (Conversation.TYPE_IM == cc.getType()) {
				if (cc.getPartners().get(0).equals(partner)) {
					return cc;
				} 
			} else {
				throw new RuntimeException("un implements");
			}
		}
		
		return null;
	}

	
	public void regOnConversationsListener(OnConversationsEvent l) {
		mListener.add(l);
	}
	public void unRegOnConversationsListener(OnConversationsEvent l) {
		mListener.remove(l);
	}
	
	
	public interface OnConversationsEvent{
		public void onNew(Conversation c);
		public void onDelete(Conversation c);
		
	}
		
}
